package controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import models.Image;
import models.Post;
import models.User;
import play.mvc.Before;
import play.mvc.Controller;
import play.mvc.With;

@With(Secure.class)
public class Admin extends Controller {

    @Before
    static void setConnectedUser() {
        if (Security.isConnected()) {
            User user = User.find("byEmail", Security.connected()).first();
            renderArgs.put("user", user.fullname);
        }
    }

    public static void index() {
        List<Post> posts = Post.find("author.email", Security.connected()).fetch();
        render(posts);
    }

    public static void form(Long id) {
        if (id != null) {
            Post post = Post.findById(id);
            render(post);
        }
        render();
    }

    public static void ajaxUploadImage(String qqfile) {
        Image image = null;
        try {
            image = new Image(qqfile, request.body);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        HashMap<String, Object> json = new HashMap<String, Object>();
        json.put("imageUrl", image.getUrl("/crop/96"));
        json.put("imageId", image.id);
        json.put("imageTitle", image.title);
        json.put("imageIsTheMainImage", image.isTheMainImage);
        json.put("success", "true");
        renderJSON(json);
    }

    public static void save(Long id, String title, String content, String tags, Long[] imageId) {
        Post post;
        if (id == null) {
            // Create post
            User author = User.find("byEmail", Security.connected()).first();
            post = new Post(author, title, content);
        } else {
            // Retrieve post
            post = Post.findById(id);
            // Edit
            post.title = title;
            post.content = content;
        }
        // Validate
        validation.valid(post);
        if (validation.hasErrors()) {
            render("@form", post);
        }
        // Save images
        ArrayList<Image> images = new ArrayList<Image>();
        if (imageId != null) {
            for (Long iid : imageId) {
                Image image = Image.findById(iid);
                // Save the title
                image.title = request.params.get("title_" + image.id);
                image.isTheMainImage = "true".equals(request.params.get("isTheMainImage_" + image.id));
                image.save();
                images.add(image);
            }
            post.images = images;
        }
        // Save
        post.save();
        index();
    }

}
